package wdn.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.jdo.PersistenceManager;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import wdn.shared.Guests;
import wdn.shared.PMF;

@SuppressWarnings("serial")
public class adminServlet extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		UserService userService = UserServiceFactory.getUserService();
	     if (!userService.isUserLoggedIn()) {
	    	 resp.sendRedirect(userService.createLoginURL("/admin"));
	     } else {
	    	 if(userService.isUserAdmin()) {
				// create the persistence manager instance
				PersistenceManager pm = PMF.get().getPersistenceManager();
			
				if(req.getParameter("action") == null) {
					String query = "select from " + Guests.class.getName();
					List<Guests> lgu = (List<Guests>) pm.newQuery(query).execute();
		
					// pass the list to the jsp
					req.setAttribute("guests", lgu);
					
					// forward the request to the jsp
					RequestDispatcher dispatcher =
					getServletContext().getRequestDispatcher("/gDisplay.jsp");
					dispatcher.forward(req, resp);
				} else {
					if(req.getParameter("action").equals("add")) {
						Guests gs = new Guests(
								req.getParameter("name"),
								req.getParameter("email"));
						try {
							pm.makePersistent(gs);
						} finally {
							pm.close();
						}
						resp.sendRedirect("admin");
					}
					else if (req.getParameter("action").equals("del")) {
						resp.setContentType("text/plain");
						resp.getWriter().println("Del");
					}
					else if (req.getParameter("action").equals("disp")) {
						resp.setContentType("text/plain");
						resp.getWriter().println("Hello, " + req.getParameter("name"));
					}
					resp.setContentType("text/plain");
					resp.getWriter().println("What?");
				}
	    	 } else {
					resp.setContentType("text/html");
					resp.getWriter().println("Only Admin can do this.<P> <A HREF=\"" + userService.createLogoutURL("/admin"));
					resp.getWriter().println("\">Logout</a>");
	    	 }
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
			doGet(req, resp);
	}
}
